#include <stdio.h>
#include "ts_list.h"

// 分配
TSELEM* TSELEM_malloc() {
	TSELEM *elem = (TSELEM*)os_calloc(sizeof(TSELEM));
	if(!elem) return NULL;

	PRGELEM_LIST_init(&elem->prg_list);
	PKTELEM_LIST_init(&elem->pat_pkt_list);
	PKTELEM_LIST_init(&elem->pmt_pkt_list);
	PKTELEM_LIST_init(&elem->sdt_pkt_list);
	elem->cc_buf = (uint8_t*)os_calloc(0x1FFF + 1); // 需在堆上分配最多pid数量的cc空间

	return elem;
}

// 释放
void TSELEM_free(TSELEM *elem) {
	if(!elem) return;

	PRGELEM_LIST_free(&elem->prg_list    );
	PKTELEM_LIST_free(&elem->pat_pkt_list);
	PKTELEM_LIST_free(&elem->pmt_pkt_list);
	PKTELEM_LIST_free(&elem->sdt_pkt_list);
	os_free(elem->cc_buf);

	os_free(elem);
}


// 调用 list.h 中的宏模板, 展开函数定义
LIST_XXXX(TSELEM, node);


// 写文件的函数定义
void TSELEM_LIST_write_file(LIST *ts_list, int idx, char *path) {
	FILE *pfile;
	TSELEM *ts_elem;
	int file_size;

	if(!ts_list || !path) return;

	ts_elem = TSELEM_LIST_get(ts_list, idx);
	if(!ts_elem)  return;

	pfile = fopen(path, "wb");
	if(!pfile) return;

	for(file_size = 0; file_size < 50 * 1024 * 1024; ) {
		file_size += PKTELEM_LIST_write_file(&ts_elem->pat_pkt_list, pfile, ts_elem->cc_buf);
		file_size += PKTELEM_LIST_write_file(&ts_elem->pmt_pkt_list, pfile, ts_elem->cc_buf);
		file_size += PKTELEM_LIST_write_file(&ts_elem->sdt_pkt_list, pfile, ts_elem->cc_buf);
	}

	fclose(pfile);
}
